﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Xml.Linq;
using System.Threading;

namespace Chat_WebServer.Controllers
{
    public class FriendListController : ApiController
    {
        // Lay danh sach ban be va cap nhat tinh trang
        public IEnumerable<MyFriend> Get(string user)
        {
            List<MyFriend> friends = new List<MyFriend>();
            using (var db = new AccountEntities())
            {
                var temp = db.Friends.ToList().FirstOrDefault(f => f.UserName.Trim() == user);
                XElement xFriends = XElement.Parse(temp.Friends);
                foreach (XElement friend in xFriends.Elements())
                {
                    MyFriend f = new MyFriend();
                    string username = friend.Value;
                    f.Username = username;
                    if (AccountController.onlines.IndexOf(username) >= 0)
                        f.IsOnl = 1;
                    else
                        f.IsOnl = 0;
                    f.Position = GetPositonByUserName(username);
                    friends.Add(f);
                }
                if (friends.Count > 0)
                    return friends;
                return null;
            }
        }


        private Coordinate GetPositonByUserName(string username)
        {
            using (var db = new AccountEntities())
            {
                var user = db.Accounts.ToList().FirstOrDefault(a => a.Username.Trim() == username);
                Coordinate coor = new Coordinate();
                coor.Latitude = (user.Latitude == null) ? 0 : (float)user.Latitude;
                coor.Longitude = (user.Latitude == null) ? 0 : (float)user.Longitude;
                return coor;
            }
        }
    }
}
